package tools

import (
	"fmt"
	"krm-backend/config"
	"krm-backend/controllers"
	"krm-backend/utils/logs"
	"net/http"
	"time"

	"github.com/dotbalo/kubeutils/kubeutils"
	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
)

func Yaml(r *gin.Context) {
	logs.Debug(nil, "通过yaml创建或更新资源")

	var info controllers.Info
	kubeconfig := controllers.NewInfo(r, &info, "更新成功")
	//改为接口形式的创建
	instance, err := kubeutils.NewTools(kubeconfig)
	// logs.Error(map[string]interface{}{"msg": err.Error()}, "创建工具失败")
	if err != nil {
		logs.Error(map[string]interface{}{"msg": err.Error()}, "创建工具失败")
		info.ReturnData.Message = err.Error()
		info.ReturnData.Status = 400
		r.JSON(http.StatusOK, info.ReturnData)
	}
	var errMsg string
	switch info.Method {
	case "Create":
		info.ReturnData.Message = "创建成功"
		errMsg, _ = instance.Create(info.Yaml)
	case "Update":
		errMsg, _ = instance.Update(info.Yaml)
	case "Apply":
		errMsg, _ = instance.Apply(info.Yaml)
	}
	if errMsg != "" {
		info.ReturnData.Message = errMsg
	}
	r.JSON(http.StatusOK, info.ReturnData)
}

// 定义upgrader用于升级http请求
var upgrader = websocket.Upgrader{
	ReadBufferSize:  1024,
	WriteBufferSize: 1024,
	CheckOrigin: func(r *http.Request) bool {
		return true
	},
}

func Ping(r *gin.Context) {
	// 🧪 新增日志：查看请求是否到达
	logs.Debug(map[string]interface{}{
		"method":   r.Request.Method,
		"url":      r.Request.URL.String(),
		"clientIP": r.ClientIP(),
	}, "WebSocket请求到达")
	returnData := config.ReturnData{}
	//升级request为websocket协议
	ws, err := upgrader.Upgrade(r.Writer, r.Request, nil)
	if err != nil {
		// ❌ 升级失败时记录详细信息
		logs.Error(map[string]interface{}{
			"error":    err.Error(),
			"method":   r.Request.Method,
			"url":      r.Request.URL.String(),
			"clientIP": r.ClientIP(),
		}, "WebSocket升级失败")
		//说明ws升级失败
		logs.Error(map[string]interface{}{"msg": err.Error()}, "websocket升级失败")
		returnData.Message = err.Error()
		returnData.Status = 400
		r.JSON(http.StatusOK, returnData)
		return
	}
	// ✅ 升级成功
	logs.Info(map[string]interface{}{
		"clientIP": r.ClientIP(),
	}, "WebSocket连接建立成功")
	//说明升级成功的
	defer ws.Close()
	for {
		//收消息
		//msgType: 消息类型
		//msgType: 1 文本消息
		//msgType: 2 二进制消息
		//msgType: 8 关闭消息
		msgType, msgContent, err := ws.ReadMessage()
		if err != nil {
			//接受消息时失败的
			logs.Warning(map[string]interface{}{"msg": err.Error()}, "接受消息失败")
			continue
		}
		msgString := string(msgContent)
		//打印消息内容
		logs.Debug(map[string]interface{}{"msg": msgString}, "接受消息成功")
		//创建打印信息
		msgRespone := fmt.Sprintf("你发送的消息是：%s,发送时间:%v", msgString, time.Now())
		//发送消息
		if err := ws.WriteMessage(msgType, []byte(msgRespone)); err != nil {
			//发送消息时失败的
			logs.Error(map[string]interface{}{"msg": err.Error()}, "回复消息失败")
			continue
		}
	}
}
